﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RecruitStudents.Utility;
using RecruitStudents.Utility.Helper;
using RecruitStudents.Client.BLL;
using RecruitStudents.Utility.Model;
using RecruitStudents.Utility.Const;
using System.Net;
using System.Runtime.InteropServices;
using DevExpress.XtraEditors;
using System.Net.NetworkInformation;
using RecruitStudents.Client.Loading;
using System.Threading;

namespace RecruitStudents.Client
{
    public partial class Login : BaseForm
    {
        RecruitStudents.Utility.UsbKey.SoftKey2K ytsoftkey;
        public static string KeyPath;

        ServiceComm service = new ServiceComm();
        public Login()
        {
            InitializeComponent();
            this.AcceptButton = this.btnLogin;
        }
        private void Login_Load(object sender, EventArgs e)
        {
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            //初始化我们的操作加密锁的类
            //ytsoftkey = new RecruitStudents.Utility.UsbKey.SoftKey2K();
            //这个用于判断系统中是否存在着加密锁。不需要是指定的加密锁,
            //if (ytsoftkey.FindPort(0, ref KeyPath) != 0)
            //{
            //    DevHelper.ShowErrorMessageBox("未找到加密锁,请插入加密锁后，再进行操作。");
            //    return;
            //}
            if (string.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                DevHelper.ShowErrorMessageBox("请选择输入登录名称！");
                txtUserName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtPassWord.Text.Trim()))
            {
                DevHelper.ShowErrorMessageBox("请选择输入登录密码！");
                txtPassWord.Focus();
                return;
            }

            #region UsbKey
            //从加密锁中读取字符串,使用默认的读密码
            //string outstring = "";
            //short mylen;
            //mylen = 20;//注意这里的6是长度，要与写入的字符串的长度相同

            //ytsoftkey.YReadString(ref outstring, 0, mylen, "ffffffff", "ffffffff", KeyPath);
            //int ileng = 0;

            //char[] chars = outstring.ToCharArray();
            //char strSpace = chars[19];

            //for (int i=0; i< chars.Length;  i++ )
            //{
            //    if (chars[i] == strSpace)
            //    {
            //        ileng = i;
            //        break;
            //    }       
            //}

            //outstring = outstring.Substring(0, ileng);

            //if (outstring.Trim() != txtUserName.Text.Trim())
            //{
            //    DevHelper.ShowErrorMessageBox("登录名和UsbKey不匹配 ！");
            //    txtUserName.Focus();
            //    return;
            //}
            #endregion

            LoginUser();
        }
        private void LoginUser()
        {
            DateTime nowClient = DateTime.Now;
            DateTime nowSystem = service.GetSystemDateTime();
            int mulic = DateDiff(nowClient, nowSystem);
            if (mulic > 5)
            {
                DevHelper.ShowErrorMessageBox("当前机器时间与服务器时间(" + nowSystem.DateTimeToyyyy_MM_dd_HH_mm() + ")不对，请调整好时间再进行登陆！");
                return;
            }
            bool result = false;
            result = LoginModel();
            if (result)
            {
                this.Close();
            }
            else
            {
                SessionerHelper.UserLoginIP = string.Empty;
                SessionerHelper.UserID = string.Empty;
                SessionerHelper.UserType = string.Empty;
                SessionerHelper.LoginName = string.Empty;
                SessionerHelper.UserName = string.Empty;
                SessionerHelper.UserRight = string.Empty;
            }
        }

        private bool LoginModel()
        {
            TB_Sys_User model = service.LoginUser(txtUserName.Text, txtPassWord.Text);
            if (model != null)
            {
                if (model.IsActive == "0")
                {
                    DevHelper.ShowErrorMessageBox("登陆失败:改帐号已经停用，请通知管理员进行开启！");
                    return false;
                }
                using (DataTable dt = service.GetSystemInfoDataTable(ConstSystem.SystemYear + "," + ConstSystem.SystemSchoolNo + "," + ConstSystem.SystemSchoolName))
                {
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        DataRow[] drs = dt.Select("SystemInfoID='" + ConstSystem.SystemYear + "'");
                        if (drs.Length > 0)
                        {
                            SessionerHelper.SystemYear = drs[0]["SystemInfoName"].ToString();
                        }
                        drs = dt.Select("SystemInfoID='" + ConstSystem.SystemSchoolNo + "'");
                        if (drs.Length > 0)
                        {
                            SessionerHelper.SystemSchoolNo = drs[0]["SystemInfoName"].ToString();
                        }
                        drs = dt.Select("SystemInfoID='" + ConstSystem.SystemSchoolName + "'");
                        if (drs.Length > 0)
                        {
                            SessionerHelper.SystemSchoolName = drs[0]["SystemInfoName"].ToString();
                        }
                    }
                }
                if (model.Type != "0")
                {
                    using (DataTable dt = service.GetRoleAuth(model.RoleID))
                    {
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            StringBuilder str = new StringBuilder();
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (str.Length == 0)
                                {
                                    str.Append(dr["ModuleID"].ToString());
                                }
                                else
                                {
                                    str.Append("," + dr["ModuleID"].ToString());
                                }
                            }
                            SessionerHelper.UserLoginIP = GetLoginIP(); ;
                            string[] strs = GetMacString();
                            if (strs.Length > 0)
                            {
                                SessionerHelper.UserMacNo = strs[0];
                            }
                            else
                            {
                                DevHelper.ShowErrorMessageBox("获取电脑Mac地址出现异常！");
                                return false;
                            }
                            SessionerHelper.UserID = model.UserID;
                            SessionerHelper.UserType = model.Type;
                            SessionerHelper.LoginName = txtUserName.Text;
                            SessionerHelper.UserName = model.Name;
                            SessionerHelper.UserRight = str.ToString();
                        }
                        else
                        {
                            DevHelper.ShowErrorMessageBox("登陆失败:该用户还没有分配任何权限");
                            return false;
                        }
                    }
                }
                else
                {
                    SessionerHelper.UserLoginIP = GetLoginIP();
                    string[] str = GetMacString();
                    if (str.Length > 0)
                    {
                        SessionerHelper.UserMacNo = str[0];
                    }
                    else
                    {
                        DevHelper.ShowErrorMessageBox("获取电脑Mac地址出现异常！");
                        return false;
                    }
                    SessionerHelper.UserID = model.UserID;
                    SessionerHelper.UserType = model.Type;
                    SessionerHelper.LoginName = txtUserName.Text;
                    SessionerHelper.UserName = model.Name;
                }
                return true;
            }
            else
            {
                DevHelper.ShowErrorMessageBox("登陆失败:用户名或密码错误");
                return false;
            }
        }

        private string GetLoginIP()
        {
            try
            {
                System.Net.IPAddress addr;
                addr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
                return addr.ToString();
            }
            catch
            {
                return "127.0.0.1";
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region 返回时间差
        private int DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            return ts.Minutes;
        }
        #endregion
        public static string[] GetMacString()
        {
            string strMac = "";
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface ni in interfaces)
            {
                if (ni.OperationalStatus == OperationalStatus.Up)
                {
                    strMac += ni.GetPhysicalAddress().ToString() + "|";
                }
            }
            return strMac.Split('|');

        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string[] str = GetMacString();
            if (str.Length > 0)
            {
                DevHelper.ShowInfoMessageBox("您的Mac地址是：" + str[0].ToSafeString() + "\r\n您的IP地址是：" + GetLoginIP());
            }
        }
    }
}
